package com.house.java.action.secondhouse;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.house.java.biz.SecondHouseBusiness;
import com.house.java.model.SecondHouse;
import com.house.java.util.SecondHouseUtils;


public class SecondHouseAddServlet extends HttpServlet {

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//factory为解析器提供解析时的缺省的配置
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//创建一个解析器
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 创建  NewHouse 对象
		SecondHouse house = new SecondHouse();
		SecondHouseUtils utils = new SecondHouseUtils();
		//使用解析器
		try {
			//FileItem对象封装了一个表单域中的所有数据
			List<FileItem> items = sfu.parseRequest(request);
			//可以通过FileItem对象提供的方法来获得表单中的数据
			for (int i = 0; i < items.size(); i++) {
				FileItem item = items.get(i);
				if(item.isFormField()){
					//除了input type="file"之外的表单域
					utils.setSecondHouse(house, item.getFieldName(), item.getString());
				}else {
					//type="input" 的表单域
					//将表单域中的数据以文件的方式保存到服务器端
						//获得实际部署时的物理路径
						ServletContext sc = getServletContext();
						String path = sc.getRealPath("/upload/newHouse");
						String fileName = item.getName();//获得上传文件的名称
						if(fileName.equals("")){
							continue;
						}
						File file = new File(path+File.separator+fileName);
						//System.out.println("."+File.separator+fileName);
						item.write(file);
						utils.setSecondHouse(house, "images", file.getPath());
				}
			}
			SecondHouseBusiness biz = new SecondHouseBusiness();
			boolean result = biz.addSecondHouse(house);
			request.setAttribute("result", result);
		} catch (Exception e) {
			log(e.getMessage());
		}
		
		
		
	}

}
